<template>

  <div>
    <el-table
        :data="tableData"
        border
        style="width: 100%">
      <el-table-column
          fixed
          prop="id"
          label="id"
          width="150">
      </el-table-column>
      <el-table-column
          prop="cropId"
          label="作物编号"
          width="120">
      </el-table-column>
      <el-table-column
          prop="sid"
          label="仓库id"
          width="120">
      </el-table-column>
      <el-table-column
          prop="pid"
          label="零销售id"
          width="120">
      </el-table-column>
      <el-table-column
          prop="startAddress"
          label="开始地址"
          width="120">
      </el-table-column>
      <el-table-column
          prop="endAddress"
          label="结束地址"
          width="300">
      </el-table-column>
      <el-table-column
          prop="status"
          label="订单状态"
          width="120">
      </el-table-column>
      <el-table-column
          prop="haulerName"
          label="司机名字"
          width="120">
      </el-table-column>
      <el-table-column
          prop="cname"
          label="农作物名称"
          width="120">
      </el-table-column>
      <el-table-column
          prop="completionTime"
          label="完成时间"
          width="120">
      </el-table-column>
      <el-table-column
          fixed="right"
          label="操作"
          width="100">
        <template slot-scope="scope">
          <el-button @click="handleClick(scope.row)" v-if="scope.row.status==0" type="text" size="small">待发出</el-button>
          <el-button @click="handleClick(scope.row)" v-if="scope.row.status==1" type="text" size="small">运输中</el-button>
          <el-button v-if="scope.row.status==2" type="text" size="small">已送达</el-button>
          <el-button @click="initAMap(scope.row)"  type="text" size="small">追踪链路</el-button>
          <el-button @click="initmyMap(scope.row)"  type="text" size="small">追踪小车</el-button>
          <el-button @click="getPosition(scope.row)"  type="text" size="small">获取位置</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @current-change="handleCurrentChange"
        :page-size="size"
        layout="total, prev, pager, next"
        :total="total">
    </el-pagination>
    <el-drawer size="80%" :visible.sync="playTrackView" :show-close="false" :with-header="false">
      <el-divider content-position="left">物流追踪</el-divider>
      <div id="container" className="map"></div>
      <div id="panel"></div>
    </el-drawer>


  </div>

</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
export default {
  name: "WlView",
  data(){
    return{
      formLabelWidth:'120px',
      form:{},
      dialogFormVisible:false,
      driverData:[],
      tradesmanData:[],
      tableData:[],
      playTrackView:false,
      markerPosition: [] ,
      gps:{},
      size:3,
      total:0,
      current:1,
    }
  },
  mounted() {
    // window._AMapSecurityConfig = {
    //   securityJsCode: "f4d27549e10b2ca24bb8133e532ab1de",
    // };
  }
  ,methods:{
    getPosition(row) {
        var item = localStorage.getItem("position");
        alert("当前经纬度为"+item);
        this.gps.indate=new Date();
        this.gps.hname=row.haulerName;
        this.gps.gps=item;
        this.gps.cname=row.cname;
        this.axios.post("/cropservice/outbound/saveTdtrance",this.gps).then(res=> {
            if (res.data.code==200){
              this.$message.success("添加gps信息成功");
            }
        }
      )

    },
    initAGPSMap() {
      window._AMapSecurityConfig = {
        //权限服务安全密钥
        securityJsCode: "e94e0e0afa1842f9327e06ca955297a7",
      };
      AMapLoader.load({
        key: "d0a13e507309316024509a088bf8cfee", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
          .then((AMap) => {
            AMap.plugin('AMap.Geolocation', function() {
              var geolocation = new AMap.Geolocation({
                enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                timeout: 10000, // 设置定位超时时间，默认：无穷大
                offset: [10, 20],  // 定位按钮的停靠位置的偏移量
                zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                position: 'RB' //  定位按钮的排放位置,  RB表示右下
              })
              geolocation.getCurrentPosition(function(status,result){
                if(status=='complete'){
                  // alert(this.markerPosition)
                  onComplete(result)
                }else{
                  onError(result)
                }
              });

              function onComplete (data) {
                var markerPosition=[data.position.lng,data.position.lat]
                localStorage.setItem("position",markerPosition);
                console.log(data.position.lng)
                console.log(data.position.lat)
                // data是具体的定位信息
              }

              function onError (data) {
                console.log(data)
                // 定位出错
              }
            })
          })
          .catch((e) => {
            console.log(e);
          });
    },
    initAMap(row) {
      this.playTrackView=true;
      window._AMapSecurityConfig = {
        securityJsCode: "e94e0e0afa1842f9327e06ca955297a7",
      };
      AMapLoader.load({
        key: "d0a13e507309316024509a088bf8cfee", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale", "AMap.Driving"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
          .then((AMap) => {
            const map = new AMap.Map("container", {
                  // 设置地图容器id
                  viewMode: "2D", // 是否为3D地图模式
                  resizeEnable: true,
                  center: row.startIp.split(","),
                  zoom: 9
                })
            ;
            AMap.plugin(["AMap.Driving"], function () {
                  const driving = new AMap.Driving({
                    map: map,
                    panel: "panel",
                  });
                  const startLngLat = row.startIp.split(",") //起始点坐标
                  const endLngLat = row.endIp.split(",") //终点坐标
                  driving.search(startLngLat, endLngLat, function (status, result) {
                    if (status === "complete") {
                      //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
                      //查询成功时，result 即为对应的驾车导航信息
                      console.log(result);
                    } else {
                      console.log("获取驾车数据失败：" + result);
                    }
                  });
                },
            );
          })
          .catch((e) => {
            console.log(e);
          });
    },
    initmyMap(row) {
      console.log(row)
      this.playTrackView=true;

      window._AMapSecurityConfig = {
        //权限服务安全密钥
        securityJsCode: "e94e0e0afa1842f9327e06ca955297a7",
      };
      AMapLoader.load({
        key: "d0a13e507309316024509a088bf8cfee", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
          .then((AMap) => {
            console.log([row.endIp])
            const lineArr = [
              row.startIp.split(","),
              row.endIp.split(","),
              // []
            ];
            var map = new AMap.Map("container", {
              // 设置地图容器id
              viewMode: "3D", // 是否为3D地图模式
              resizeEnable: true,
              center: row.startIp.split(","),//允许地图容器在窗口大小改变时自动调整地图大小，保持地图的可视性。
              zoom: 9 //用于控制地图的细节级别。数字越大，表示地图被放大得越详细，可以看到更小的地理特征；数字越小，表示地图被缩小，显示的区域范围更大，但细节更少。
            });
            var marker = new AMap.Marker({
              position: row.startIp.split(","),
              icon: 'https://webapi.amap.com/images/car.png',
              //坐标偏移
              offset: new AMap.Pixel(-26, -13),
              autoRotation: true,
              angle: -90,
              map: map
            });
            // 绘制轨迹路线
            var polyline = new AMap.Polyline({
              map: this.map,
              //这里替换自己的坐标数据
              path: lineArr,
              borderWeight: 2, // 线条宽度，默认为 1
              strokeColor: 'red', // 线条颜色
              lineJoin: 'round' // 折线拐点连接处样式
            });
            map.add(polyline);
            //调用方法开启动画
            marker.moveAlong(lineArr, 30000);
          })
          .catch((e) => {
            console.log(e);
          });
    },

    handleClick(att){
      this.form.sid=att.id;
      this.form.tid=att.pid;
      this.form.source=att.cname;
      this.form.cropId=att.cropId;

      this.axios.post("cropservice/outbound/changeStatus",this.form).then(res=>{
        if (res.data.code==200){
          alert(res.data.data)
        }else {
          alert(res.data.msg)
        }
        this.transportShow()
      })
    },
    add(){
      alert("添加成功!!!");
    },
    openAdd(){
      this.dialogFormVisible=true;
      //this.form={};
      //this.form.num=1;
    },
    // 零售商下拉框数据
    tradesmanSho(){
      this.axios.get("/cropservice/delivery/tradesmanList").then(r=>{
        if(r.data.code==200) {
          this.tradesmanData=r.data.data;
        }
      })
    },
    // 司机下拉框数据
    driverShow(){
      this.axios.get("/cropservice/delivery/driverList").then(r=>{
        if(r.data.code==200) {
          this.driverData=r.data.data;
        }
      })
    },
    handleCurrentChange(val) {
      this.current = val;
      this.transportShow();
    },
    // 物流列表
    transportShow(){
      this.axios.get("/cropservice/delivery/transportList?current="+this.current+"&size="+this.size).then(r=>{
        if(r.data.code==200) {
          this.tableData=r.data.data.list;
          this.total=r.data.data.total;
        }
      })
    },
  },created() {
    // 司机下拉框数据
    this.driverShow();
    // 零售商下拉框数据
    this.tradesmanSho();
    // 物流列表
    this.transportShow();
    //
    this.initAGPSMap();
    //dinsgshi
    this.startPolling();
  },

}
</script>

<style scoped>
#container {
  width: 100%;
  height: 800px;
}
</style>